import {openDB} from 'idb';
import {v4 as uuidv4} from 'uuid';

const DB_NAME = 'file-db';
const STORE_NAME = 'file-store';

export const dbPromise = openDB(DB_NAME, 1, {
  upgrade(db) {
    const objectStore = db.createObjectStore(STORE_NAME, {keyPath: 'id'});
    objectStore.createIndex('title', 'title');
    objectStore.createIndex('created', 'created');
    objectStore.createIndex('updated', 'updated');

  },
});

export const IndexedDB = {
    async getAllFiles() {
      const db = await dbPromise;
      const tx = db.transaction(STORE_NAME, 'readonly');
      const store = tx.objectStore(STORE_NAME);
      const index = store.index('updated');
      const files = [];

      const p = new Promise((resolve, reject) => {
        const req = index.openCursor(null, 'prev');
        console.log("openCursor:" + req)
        req.onsuccess = (event) => {
          console.log("onsuccess:" + event)
          const cursor = event.target.result;
          if (cursor) {
            files.push(cursor.value);
            cursor.continue();
          } else {
            resolve(files);
          }
        };

        req.onerror = () => {
          reject(req.error);
        };
      });
      p.then(function (value) {//成功的形参
        console.log("成功" + value);
      }, function (reason) {//失败的形参
        console.log("失败" + reason);
      });
      p.catch(function (reason) {
        console.log("失败1" + reason);
      });
      p.finally(function (value) {//成功的形参
        console.log("成功2" + value);
      }, function (reason) {//失败的形参
        console.log("失败2" + reason);
      });
      console.log("失败3"+p);
      return p;
    },
// async getAllFiles() {
//   const db = await dbPromise;
//   const tx = db.transaction(STORE_NAME, 'readonly');
//   const store = tx.objectStore(STORE_NAME);
//   return store.getAll();
// },
    async addFile(file) {
      const db = await dbPromise;
      const tx = db.transaction(STORE_NAME, 'readwrite');
      const store = tx.objectStore(STORE_NAME);
      const id = uuidv4();
      await store.add({...file, id, created: new Date(), updated: new Date()});
      return tx.complete;
    }
    ,

    async updateFile(file) {
      const db = await dbPromise;
      const tx = db.transaction(STORE_NAME, 'readwrite');
      const store = tx.objectStore(STORE_NAME);
      const updatedFile = {...file, updated: new Date()};
      await store.put(updatedFile);
      return tx.complete;
    }
    ,

    async deleteFile(id) {
      const db = await dbPromise;
      const tx = db.transaction(STORE_NAME, 'readwrite');
      const store = tx.objectStore(STORE_NAME);
      await store.delete(id);
      return tx.complete;
    }
    ,

    async searchFiles(query) {
      const db = await dbPromise;
      const tx = db.transaction(STORE_NAME, 'readonly');
      const store = tx.objectStore(STORE_NAME);
      const index = store.index('title');
      const results = await index.getAll(IDBKeyRange.bound(query, query + '\uffff'));
      return results;
    }
  }
;
